
const express = require("express");
const WebSocket = require("ws");

const app = express();
const router = express.Router();
const { OrderModel, ChatModel, ShopModel, UseModel } = require("../mongodb/db.js");

// 封装WebSocket处理逻辑
function setupWebSocketServer(server) {
  const wss = new WebSocket.Server({ server });

  wss.on("connection", async (ws) => {
    try {
      let data = await ChatModel.find();
      ws.send(JSON.stringify(data));

      // const intervalId = setInterval(async () => {
      //   let data = await ChatModel.find();
      //   ws.send(JSON.stringify(data));
      // }, 1000);

      ws.on("message", async (message) => {
        try {
          const parsedMessage = JSON.parse(message);
          console.log("收到客户端消息：", parsedMessage);

          await ChatModel.create(parsedMessage);
          broadcastData(wss, await ChatModel.find());
        } catch (error) {
          console.error("处理消息时出错：", error);
        }
      });

      ws.on("close", () => {
        console.log("客户端已断开连接");
        // clearInterval(intervalId);
      });
    } catch (error) {
      console.error("WebSocket连接时出错：", error);
    }
  });

  wss.on("error", (error) => {
    console.error("WebSocket服务器错误", error);
  });
}

// 封装数据广播逻辑
function broadcastData(wss, data) {
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(data));
    }
  });
}

// 路由处理
router.get("/getChat", async (req, res) => {
  console.log("获取聊天记录");
  try {
    let data = await ChatModel.find();
    res.send({ data });
  } catch (error) {
    console.error("获取聊天记录时出错：", error);
    res.status(500).send("服务器错误");
  }
});

router.get("/get", async (req, res) => {
  try {
    let data = await UseModel.aggregate([
      {
        $lookup: {
          from: "shops",
          localField: "sid",
          foreignField: "_id",
          as: "shopList",
          pipeline: [
            {
              $lookup: {
                from: "chat",
                localField: "_id",
                foreignField: "tid",
                as: "chatList",
              },
            },
          ],
        },
      },
    ]);
    let data1 = await ChatModel.find();
    res.send({ data, data1 });
  } catch (error) {
    console.error("获取数据时出错：", error);
    res.status(500).send("服务器错误");
  }
});

router.get("/gShop", async (req, res) => {
  try {
    let data = await ShopModel.aggregate([
      {
        $lookup: {
          from: "use-shop",
          localField: "_id",
          foreignField: "sid",
          as: "orderList",
          pipeline: [
            {
              $lookup: {
                from: "chat",
                localField: "_id",
                foreignField: "uid",
                as: "chatList",
              },
            },
          ],
        },
      },
    ]);
    let data1 = await ChatModel.find();
    res.send({ data, data1 });
  } catch (error) {
    console.error("获取商店数据时出错：", error);
    res.status(500).send("服务器错误");
  }
});

router.post("/updateChat", async (req, res) => {
  await ChatModel.updateMany({ is_read: true });
  res.send({
    code: 200,
    msg: "更新成功",
  });
});

// 注册路由
app.use(router);

// 启动HTTP服务器，监听3005端口
const server = app.listen(3005, () => {
  console.log("Express服务器已启动，监听3005端口");
});

// 处理HTTP服务器错误
server.on("error", (error) => {
  console.error("Express服务器错误", error);
});

// 设置WebSocket服务器
setupWebSocketServer(server);

// 设置WebSocket监管4000端口
const wssMonitor = new WebSocket.Server({ port: 4000 });

wssMonitor.on("connection", async (ws) => {
  try {
    console.log("4000端口的客户端已连接");

    // const intervalId = setInterval(async () => {
    let data = await OrderModel.find();
    ws.send(JSON.stringify(data));
    // }, 1000);

    ws.on("message", async (message) => {
      try {
        const parsedMessage = JSON.parse(message);
        console.log("收到监控客户端消息", parsedMessage);

        await OrderModel.create(parsedMessage);
        broadcastData(wssMonitor, await OrderModel.find());
      } catch (error) {
        console.error("处理监控消息时出错：", error);
      }
    });

    ws.on("close", () => {
      console.log("监控客户端已断开连接");
      // clearInterval(intervalId);
    });
  } catch (error) {
    console.error("监控WebSocket连接时出错：", error);
  }
});

wssMonitor.on("error", (error) => {
  console.error("WebSocket监控服务器错误", error);
});

module.exports = app;

